import { versionCore } from './version-core';
import { versionCompatibility } from './version-compatibility';
import { packageCore } from './package-core';
import fs from 'fs';
import path from 'path';
import { aiEngine } from './ai-engine';

/**
 * 全局兼容树管理器
 */
export class CompatibilityTree {
  private static instance: CompatibilityTree;
  private treeStructure: Record<string, any> = {};
  private basePath: string = packageCore.getInternalPath('core') || process.cwd();

  public constructor() {
    // 智能依赖分析
    const requiredDependencies = ['path', 'fs', 'util'];
    const missingDeps = requiredDependencies.filter(dep => !require.resolve(dep));
    
    if (missingDeps.length > 0) {
      console.log(`[AI-分析] 缺少必要依赖: ${missingDeps.join(', ')}`);
      missingDeps.forEach(dep => {
        console.log(`[AI-建议] ${dep}是核心依赖，建议通过npm install ${dep}安装`);
      });
    }

    // 注册类型并提供智能补全
    aiEngine.registerType('CompatibilityTree', {
      methods: ['setBasePath', 'resolveDependency', 'validateCompatibility']
    });

    this.initTree();
  }

  public static getInstance(): CompatibilityTree {
    if (!CompatibilityTree.instance) {
      CompatibilityTree.instance = new CompatibilityTree();
      console.log('[AI-管理] 已创建智能优化后的CompatibilityTree实例');
    }
    return CompatibilityTree.instance;
  }

  private compatiblePackages: Record<string, string> = {};
  private compatibleApis: Set<string> = new Set();

  public isPackageCompatible(pkgName: string): boolean {
    console.log(`[AI-检查] 包兼容性: ${pkgName}`);
    return pkgName in this.compatiblePackages;
  }

  public isApiCompatible(namespace: string, apiName: string): boolean {
    const fullApiName = `${namespace}.${apiName}`;
    console.log(`[AI-检查] API兼容性: ${fullApiName}`);
    return this.compatibleApis.has(fullApiName);
  }

  public addCompatiblePackage(pkgName: string, versionRange: string): void {
    console.log(`[AI-记录] 添加兼容包: ${pkgName}@${versionRange}`);
    this.compatiblePackages[pkgName] = versionRange;
  }

  public addCompatibleApi(namespace: string, apiName: string): void {
    const fullApiName = `${namespace}.${apiName}`;
    console.log(`[AI-记录] 添加兼容API: ${fullApiName}`);
    this.compatibleApis.add(fullApiName);
  }

  /**
   * 初始化兼容树结构
   */
  private initTree() {
    this.treeStructure = {
      // 代码模块
      code: {
        core: versionCore.getCompatibleVersion('core'),
        adapters: versionCore.getCompatibleVersion('adapters'),
        platform: versionCore.getCompatibleVersion('platform'),
        wasm: versionCore.getCompatibleVersion('wasm')
      },
      // 配置文件
      config: {
        vscode: 'latest',
        eslint: 'latest',
        prettier: 'latest',
        jest: 'latest',
        typescript: 'latest'
      },
      // 测试文件
      test: {
        core: versionCore.getCompatibleVersion('core'),
        adapters: versionCore.getCompatibleVersion('adapters')
      },
      // 文档
      docs: 'latest',
      // 静态资源
      assets: 'shared',
      // 环境配置
      env: {
        node: process.version,
        system: 'shared'
      }
    };
  }

  /**
   * 获取文件兼容路径
   */
  public getCompatiblePath(filePath: string): string {
    // 转换为包内路径
    const pkgPath = filePath.startsWith('pkg://') ? 
      packageCore.resolveExternalPath(filePath) : filePath;
    
    const relativePath = path.relative(this.basePath, pkgPath);
    const parts = relativePath.split(path.sep);

    // 处理代码文件
    if (parts[0] === 'src') {
      const module = parts[1];
      const version = versionCore.getCompatibleVersion(module);
      const newPath = path.join('src', module, version, ...parts.slice(2));
      return packageCore.getExternalPath(path.join(this.basePath, newPath));
    }

    // 处理测试文件
    if (parts[0] === 'test') {
      const module = parts[1];
      const version = versionCore.getCompatibleVersion(module);
      const newPath = path.join('test', module, version, ...parts.slice(2));
      return packageCore.getExternalPath(path.join(this.basePath, newPath));
    }

    // 配置文件版本化
    if (parts[0] === '.vscode' || parts[0] === '.config') {
      const newPath = path.join(
        parts[0], 
        'v' + this.treeStructure.config[parts[0].slice(1)] || 'latest', 
        ...parts.slice(1)
      );
      return packageCore.getExternalPath(path.join(this.basePath, newPath));
    }

    // 其他文件转换为包路径
    return packageCore.getExternalPath(pkgPath);
  }

  /**
   * 构建完整兼容环境
   */
  public buildCompatibleEnvironment() {
    // 创建版本化目录结构
    this.createVersionedDirectories();
    
    // 链接共享资源
    this.linkSharedResources();
    
    // 生成环境配置
    this.generateEnvConfig();
  }

  private createVersionedDirectories() {
    // 创建版本化代码目录
    for (const module of ['core', 'adapters', 'platform', 'wasm']) {
      const version = versionCore.getCompatibleVersion(module);
      fs.mkdirSync(path.join('src', module, version), { recursive: true });
      fs.mkdirSync(path.join('test', module, version), { recursive: true });
    }

    // 创建版本化配置目录
    for (const config of ['vscode', 'eslint', 'prettier', 'jest']) {
      fs.mkdirSync(path.join('.config', config, 'latest'), { recursive: true });
    }
  }

  private linkSharedResources() {
    // 链接文档和静态资源
    fs.symlinkSync(path.join('docs'), path.join('compatibility-layer', 'docs'));
    fs.symlinkSync(path.join('assets'), path.join('compatibility-layer', 'assets'));
  }

  private generateEnvConfig() {
    const envConfig = {
      nodeVersion: this.treeStructure.env.node,
      compatibleModules: this.treeStructure.code,
      configVersions: this.treeStructure.config
    };
    
    fs.writeFileSync(
      path.join('compatibility-layer', 'env.json'),
      JSON.stringify(envConfig, null, 2)
    );
  }
}

export const compatibilityTree = CompatibilityTree.getInstance();